<template>
  <div class="details" v-if="skuData">
    <Heads types="details"></Heads>

    <!-- 滑动区域 -->
    <div class="content">
    <!-- 轮播 -->
      <div class="slide-container">
        <van-swipe :loop="false" @change="onChange">
          <van-swipe-item v-for="(item, i) in banner" :key="i">
            <van-image :src="item" width="100%" height="100%">
              <template v-slot:loading>
                <van-loading type="spinner" size="20" />
              </template>
            </van-image>
          </van-swipe-item>

          <div class="custom-indicator" slot="indicator">{{ current + 1 }}/{{banner.length}}</div>
        </van-swipe>
      </div>

      <div style="margin: .2rem 0">
        <van-collapse v-model="activeNames">
          <van-collapse-item name="details">
            <div slot="title" :style="{tetxAlign: 'left'}">{{skuData.goods_info.title}}</div>
            <div slot="default" :style="{tetxAlign: 'left'}">空空如也~~~</div>
          </van-collapse-item>
        </van-collapse>
      </div>

      <van-cell-group>
        <van-field label="13号仓库" readonly>
          <div slot="input"><van-icon name="clock-o" size=".4rem" style="vertical-align: middle;" />
          {{deliveryTime}}</div>
        </van-field>
        <van-field label="服务" value="全场满99包邮 | 支持7天无理由退货" readonly />
      </van-cell-group>
    </div>

    <!-- sku -->
    <div class="sku-container" :style="{'text-align':'left'}">
        <!-- v-model="showCustom" // 显示
        :sku="skuData.sku" // tree list(tree的组合) messages
        :goods="skuData.goods_info"
        :goods-id="skuData.goods_id"
        :hide-stock="skuData.sku.hide_stock" // 是否显示商品剩余库存
        :quota="skuData.quota" // 限购数，0 表示不限购
        :quota-used="skuData.quota_used" // 已经购买过的数量
        :start-sale-num="skuData.start_sale_num" // 起售
        :properties="skuData.properties" // 附加属性
        reset-stepper-on-hide // 隐藏时重置选择的商品数量
        safe-area-inset-bottom // 底部安全区适配
        :initial-sku="skuData.initialSku" //初始选中
        :message-config="messageConfig" // 信息
        :custom-sku-validator="customSkuValidator" // 提示
        ref="getSku" -->
        <van-sku
          v-model="showCustom"
          :sku="skuData.sku"
          :goods="skuData.goods_info"
          :goods-id="skuData.goods_id"
          :hide-stock="skuData.sku.hide_stock"
          :quota="skuData.quota"
          :quota-used="skuData.quota_used"
          :start-sale-num="skuData.start_sale_num"
          :properties="skuData.properties"
          reset-stepper-on-hide
          safe-area-inset-bottom
          :initial-sku="skuData.initialSku"
          :message-config="messageConfig"
          :custom-sku-validator="customSkuValidator"
          @buy-clicked="onDefineClicked"
          :show-add-cart-btn="false"
          buy-text="确定"
          ref="getSku"
        >
          <template #sku-header-price="{ price }">
            <div class="van-sku__goods-price">
              <span class="van-sku__price-symbol">￥</span>
              <span class="van-sku__price-num">{{ price }}</span>
            </div>
          </template>
          <!-- <template #sku-actions="{ skuEventBus }"> 自定义按钮不支持提醒没选 -->
        </van-sku>
      </div>

    <!-- ... -->

    <!-- 底部动作 -->
    <div v-if="skuData" class="action-container">
      <van-goods-action safe-area-inset-bottom>
        <van-goods-action-icon icon="cart-o" :info="cartNum" text="购物车" :to="{name: 'Shopcart'}" />
        <van-goods-action-icon
          class="collect-icon"
          ref="collectIcon"
          :icon="isCollect ? 'star' : 'star-o'"
          :text="isCollect ? '已收藏' : '收藏'"
          @click="onCollectClicked"
        />
        <van-goods-action-icon icon="" text="" color="#07c160" />
        <van-goods-action-button
          type="warning"
          text="加入购物车"
          @click="onShowCustom('add-cart')"
        />
        <van-goods-action-button
          type="danger"
          text="立即购买"
          @click="onShowCustom('buy')"
        />
      </van-goods-action>
    </div>

  </div>
</template>

<script>
import http from '@/utils/axios'
import { mapState, mapMutations } from 'vuex'
// import { skuData } from './data.js'
// import { LIMIT_TYPE } from './constants' // 用于限购
import Vue from 'vue'
import { Field, Sku, Toast, GoodsAction, GoodsActionButton, GoodsActionIcon, Collapse, CollapseItem } from 'vant'
Vue.use(Sku).use(Field).use(Toast).use(GoodsAction).use(GoodsActionButton).use(GoodsActionIcon).use(Collapse).use(CollapseItem)

export default {
  data () {
    return {
      activeNames: [''],
      isCollect: false,
      banner: [
        'https://img.alicdn.com/imgextra/i1/88/O1CN012FcSWb1CWLRGHhwjk_!!88-0-luban.jpg_q100.jpg',
        'https://img.alicdn.com/simba/img/TB1o6YOsqL7gK0jSZFBSutZZpXa.jpg',
        'https://img.alicdn.com/tps/i4/TB1lUY_v.T1gK0jSZFrSuwNCXXa.jpg',
        'https://img.alicdn.com/simba/img/TB1457mo7Y2gK0jSZFgSuw5OFXa.jpg',
        'https://img.alicdn.com/imgextra/i2/112/O1CN01z5O8Zo1ChKwfTT4Zs_!!112-0-luban.jpg_q100.jpg'
      ], // 轮播
      current: 0, // 轮播index
      skuData: null,
      showCustom: false, // 是否显示sku
      showStepper: false,
      showSoldout: false,
      closeOnClickOverlay: true,
      customSkuValidator: () => '请选择商品属性~',
      /**  customStepperConfig: {
      //   quotaText: '单次限购100件',
      //   stockFormatter: stock => `剩余${stock}件`,
      //   handleOverLimit: data => {
      //     const { action, limitType, quota, startSaleNum = 1 } = data
      //     if (action === 'minus') {
      //       Toast(
      //         startSaleNum > 1 ? `${startSaleNum}件起售` : '至少选择一件商品'
      //       )
      //     } else if (action === 'plus') {
      //       if (limitType === LIMIT_TYPE.QUOTA_LIMIT) {
      //         Toast(`限购${quota}件`)
      //       } else {
      //         Toast('库存不够了')
      //       }
      //     }
      //   }
      // },
      */
      messageConfig: {
        uploadImg: (file, img) =>
          new Promise(resolve => {
            setTimeout(() => resolve(img), 1000)
          }),
        uploadMaxSize: 3
      }
    }
  },
  computed: {
    ...mapState('footerModule', ['cartNum']),
    deliveryTime () {
      const dates = new Date()
      return `预计${dates.getFullYear()}/${dates.getMonth() + 1}/${dates.getDate() + 3}后发货`
    }
  },
  methods: {
    ...mapMutations('footerModule', ['FOOTERSHOW', 'FOOTERCART']),
    ...mapMutations('payModule', ['SETTYPES', 'SETOBJ']),
    onChange (index) {
      // 轮播显示页码
      this.current = index
    },
    onShowCustom (type) {
      // goods-action底部的加购和购买
      this.showCustom = true
      this.skuType = type
    },
    onCollectClicked () {
      // goods-action的收藏
      // console.log(this.isCollect )
      this.isCollect = !this.isCollect
      if (this.isCollect) {
        Toast({
          message: '收藏成功~',
          duration: 500, // 默认毫秒
          position: 'bottom'
        })
      } else {
        Toast({
          message: '取消收藏~',
          duration: 500,
          position: 'bottom'
        })
      }
    },
    searchTree (sType, sVal) {
      const arrKS = this.skuData.sku.tree.filter(treeKS => {
        return treeKS.k_s === sType
      })
      const arrV = arrKS[0].v.filter(treeV => {
        return treeV.id === sVal
      })
      return arrV[0].name
    },
    onDefineClicked () {
      // Toast('buy:' + JSON.stringify(data))
      // 点击确定按钮
      if (!this.$refs.getSku.getSkuData().selectedSkuComb) {
        Toast({
          message: '请选择商品属性~',
          closeOnClick: true
        })
      } else {
        if (this.skuType === 'buy') {
          if (sessionStorage.userInfo) {
            const token = JSON.parse(sessionStorage.userInfo).token
            if (token) {
              let obj = this.$refs.getSku.getSkuData()
              obj = { ...obj, user: token, s1: this.searchTree('s1', obj.selectedSkuComb.s1), s2: this.searchTree('s2', obj.selectedSkuComb.s2), goods_info: this.skuData.goods_info }

              this.SETTYPES('obj')
              this.SETOBJ(obj)
              this.$router.push({ name: 'Paymentpage' })
            } else {
              Toast({
                message: '未登录状态,无法操作',
                closeOnClick: true
              })
            }
          } else {
            Toast({
              message: '未登录状态,无法操作',
              closeOnClick: true
            })
          }
        } else {
          // console.log('加购')
          // 先数据库,再默认头像
          // console.log(this.$refs.getSku.getSkuData())
          if (sessionStorage.userInfo) {
            const token = JSON.parse(sessionStorage.userInfo).token
            if (token) {
              http({
                method: 'post',
                url: '/vant/addcart',
                data: {
                  token,
                  info: this.$refs.getSku.getSkuData()
                }
              }).then(res => {
                Toast({
                  message: res.data.msg,
                  closeOnClick: true
                })
                http({
                  url: '/vant/cart',
                  method: 'POST',
                  data: { user: token }
                }).then(res => {
                  if (res.data.code === 200) {
                    const num = res.data.result.map(item => {
                      return item.selectedNum
                    }).reduce((a, b) => a * 1 + b * 1)
                    this.FOOTERCART(num)
                  }
                })
              })
            } else {
              Toast({
                message: '未登录状态,无法操作',
                closeOnClick: true
              })
            }
          } else {
            Toast({
              message: '未登录状态,无法操作',
              closeOnClick: true
            })
          }
        }
      }
    }
  },
  mounted () {
    this.FOOTERSHOW(false)

    http.get('/vant/details', {
      params: {
        tradeItemId: this.$route.params.tradeItemId
      }
    }).then(res => {
      if (res.data.code === 200) {
        this.skuData = res.data.result
        this.banner = [res.data.result.goods_info.picture, ...this.banner]
      } else {
        this.skuData = null
      }
    })
  },
  destroyed () {
    this.FOOTERSHOW(true)
  }
}
</script>

<style lang="scss" scoped>
.details {
  .content {
    height: 11.5rem;
    overflow-y: auto;
    .slide-container {
      width: 100vw;
      height: 5.5rem;
      position: relative;
      .van-swipe {
        height: 100%;;
        .van-swipe__track {
          .van-swipe-item {
            width: 100%;
            height: 100%;
          }
        }
        .custom-indicator {
          position: absolute;
          right: 0.2rem;
          bottom: 0.2rem;
          width: 0.8rem;
          height: 0.4rem;
          line-height: 0.4rem;
          text-align: center;
          border-radius: 0.2rem;
          color: aliceblue;
          background: rgba(0, 0, 0, 0.3);
        }
      }
    }
  }

  .action-container {
    .van-goods-action .van-goods-action--safe-area-inset-bottom{
      .van-goods-action-icon {
        .van-icon-star {
          color: rgb(255, 80, 0);
        }
      }
    }
  }
}
</style>
